package com.eazy.lkv2.web.shiro.filter;

import java.io.IOException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.OncePerRequestFilter;
import org.apache.shiro.web.util.WebUtils;

import com.eazy.lkv2.web.shiro.UserUtil;
import com.google.gson.Gson;

/**
 * @version 1.0.0
 */
public class AuthenticatedFilter extends OncePerRequestFilter {
	
	private static final String JS = "<script type='text/javascript'>var wp=window.parent; if(wp!=null){while(wp.parent&&wp.parent!==wp){wp=wp.parent;}wp.location.href='%1$s';}else{window.location.href='%1$s';}</script>";
	private String loginUrl = "/login.do";

	static Map<String,String> filterURL = new HashMap<String,String>();
	
	// 这些不拦截
	static {
		filterURL.put("/sys/login","/sys/login");
		filterURL.put("/sys/logout","/sys/logout");
		filterURL.put("/sys/forgetpwd","/sys/forgetpwd");
		filterURL.put("/sys/index","/sys/index");
		filterURL.put("/sys/error","/sys/error");
		filterURL.put("/sys/forget","/sys/forget");
	}
	
	@Override
	protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
			throws ServletException, IOException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String url = req.getRequestURI();
		
		if(!url.contains("JSESSIONID") && !url.contains("/favicon.ico") && !url.contains("/code/code") && !url.contains(".css") && !url.contains(".js")  && !url.contains("/resources/css/") && !url.contains("/resources/lib/") && !url.contains("/resources/js/") && !url.contains("/resources/images/"))
		{
			if(!url.equals("/")) {
				if(filterURL.get(url) == null) {
					if(UserUtil.getCurrentUser() == null) {
						res.sendRedirect("/index.jsp");
					} 
				} 	
			}
		}
		chain.doFilter(request, response);
//		Subject subject = SecurityUtils.getSubject();
//		if (subject.isAuthenticated()) {
//			chain.doFilter(request, response);
//		} else {
//			identifyGuest(subject, request, response, chain);
//		}
		
	}

	protected void identifyGuest(Subject subject, ServletRequest request, ServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		redirectLogin(request, response);
	}

	protected void redirectLogin(ServletRequest request, ServletResponse response) throws IOException {
		WebUtils.saveRequest(request);
		String path = WebUtils.getContextPath((HttpServletRequest) request);
		String url = "login";
		if (StringUtils.isNotBlank(path) && path.length() > 1) {
			url = path + url;
		}

		if (isAjaxRequest((HttpServletRequest) request)) {
			response.setContentType("application/json;charset=UTF-8");
			Gson gson = new Gson();
			//response.getWriter().print(gson.toJson(Data.failure("您还没有登录!")));
		} else {
			//response.getWriter().print("<script>window.localtion.href='/sys/login'</script>");
			HttpServletResponse res = (HttpServletResponse) response;
			res.sendRedirect("/index.jsp");
		}
	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	/**
	 * 判断是否为Ajax请求 <功能详细描述>
	 * 
	 * @param request
	 * @return 是true, 否false
	 * @see [类、类#方法、类#成员]
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;
		else
			return false;
	}

}
